﻿using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Sunny.UI;
using Sunny.UI.Win32;

namespace DevelopTool.Common
{
    public static class ControlHelper
    {
        public static void AppendText(this RichTextBox rtb,string text,Color? color = null,Font font = null)
        {
            rtb.SelectionStart = rtb.TextLength;
            rtb.SelectionLength = 0;

            rtb.SelectionColor = color == null ? rtb.ForeColor : (Color)color;
            rtb.SelectionFont = font == null ? rtb.Font : font;
            rtb.AppendText(text);
            rtb.SelectionColor = rtb.ForeColor;
        }


        /// <summary>
        /// 获取控件的父级控件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="control"></param>
        /// <returns></returns>
        public static T GetParentControl<T>(this Control control) where T : class
        {
            Control currentControl = control;
            while(currentControl.Parent != null)
            {
                if(currentControl.Parent is T parentOfType)
                {
                    return parentOfType;
                }
                currentControl = currentControl.Parent;
            }
            return null;
        }


        /// <summary>
        /// 返回最里层的窗体
        /// </summary>
        /// <param name="control"></param>
        /// <returns></returns>
        public static Control GetInnerMostForm(this Control control)
        {
            return control.GetAllControls().LastOrDefault(it => it is Form);
        }


        public static string GetInnerMostFormName(this Control control)
        {
            Control ctrl = control.GetAllControls().LastOrDefault(it => it is Form);
            return ctrl == null ? control.Name : ctrl.Name;
        }


        public static void HandleRunningInstance(this Form form,int showStyle = SystemEx.SW_SHOW)
        {
            User.ShowWindowAsync(form.Handle,showStyle); //调用api函数，正常显示窗口
            User.SetForegroundWindow(form.Handle); //将窗口放置最前端。
        }
    }
}
